package com.hd.assistant.biz.manager.impl.share;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.springframework.beans.factory.annotation.Autowired;

import com.hd.assistant.biz.manager.exception.ManagerException;
import com.hd.assistant.biz.manager.share.ShareManager;
import com.hd.assistant.dal.dao.exception.DAOException;
import com.hd.assistant.dal.dao.query.share.ShareQuery;
import com.hd.assistant.dal.dao.share.ShareDAO;
import com.hd.assistant.dal.dataobject.share.Share;
import com.hd.assistant.dal.dataobject.share.ShareRecord;
import com.hd.util.CommonUtil;

public class DefaultShareManager implements ShareManager{
	@Autowired
	ShareDAO shareDAO;

	Cache cache;
	
	
	public Cache getCache() {
		return cache;
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	@Override
	public void insertShareToDB(Share share) throws ManagerException {
		try {
			this.shareDAO.insert(share);
		} catch (DAOException e) {
			throw new ManagerException("insertShareToDB",e);
		}
	}

	@Override
	public Share getShareFromCache(Long shareId) throws ManagerException {
		String key = shareId+"";
		Element e = cache.getQuiet(key);
		try{
			if(e == null){
				Share value = this.shareDAO.getShareById(shareId);
				this.cache.put(new Element(key, value));
				return value;
			}else{
				return (Share)e.getObjectValue();
			}
		}catch(Exception ee){
			throw new ManagerException("getShareFromCache",ee);
		}
	}

	@Override
	public ShareQuery getSharesByQuery(ShareQuery query)
			throws ManagerException {
		try {
			return this.shareDAO.getSharesByShareQuery(query);
		} catch (DAOException e) {
			throw new ManagerException("getSharesByQuery",e);
		}
	}

	@Override
	public Share getShareFromCache(String shareId) throws ManagerException {
		Long sid = CommonUtil.parseLong(shareId);
		if(sid == 0)
			return null;
		return this.getShareFromCache(sid);
	}

	@Override
	public void insertShareRecordToDB(ShareRecord record)
			throws ManagerException {
		// TODO Auto-generated method stub
		
	}

}
